package com.mso.BSSubtitlesDownloader.model;

import com.mso.BSSubtitlesDownloader.exceptions.RegExpException;
import com.mso.BSSubtitlesDownloader.utils.TabUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by max on 31/03/2014.
 */
public class EpisodeInfosExtracter {

    private final static int INDEX_FORM01 = 0;

    private final static int INDEX_FORM02 = 1;

    // TODO Regexp pour la récup
    private static String REGEXP_RELEASE_NAME = "([ A-Z0-9]+).";

    private EpisodeInfos episodeInfos;

    private String fileName = "";

    public EpisodeInfosExtracter(String fileName) {
        this.fileName = fileName;
    }

    public void execute() throws RegExpException {

        checkShowName(EnumRegularExpressions.REGEXP_SHOW_NAME_FORM01, 0);
    }

    private void checkShowName(EnumRegularExpressions regexpSN, Integer index) throws RegExpException {

        Pattern pattern = Pattern.compile(regexpSN.toString(), Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(fileName);

        // Si la regexp retourne 2 résultats, on traite, sinon Exception
        if (matcher.find())
        {
            episodeInfos = new EpisodeInfos();

            // Il faut remplacer tous les points par des espaces si besoin
            episodeInfos.setNom(matcher.group(1).replaceAll("[\\._]", " "));


            switch (index)
            {
            case INDEX_FORM01 :
                checkSeasonEpisode(EnumRegularExpressions.REGEXP_SEASON_EP_FORM01);

                break;
            case INDEX_FORM02 :
                checkSeasonEpisode(EnumRegularExpressions.REGEXP_SEASON_EP_FORM02);

                break;
            default :
                throw new RegExpException(fileName);
            }
        }
        else if (index < 1)
        {
            checkShowName(EnumRegularExpressions.REGEXP_SHOW_NAME_FORM02, index + 1);
        }
        else
        {
            throw new RegExpException(fileName);
        }
    }

    private void checkSeasonEpisode(EnumRegularExpressions regexpSE) throws RegExpException {
        Pattern pattern;
        Matcher matcher;
        pattern = Pattern.compile(regexpSE.toString(), Pattern.CASE_INSENSITIVE);
        matcher = pattern.matcher(fileName);

        if (matcher.find())
        {
            episodeInfos.setSaison(matcher.group(1));
            episodeInfos.setEpisode(matcher.group(2));
        }
        else
        {
            throw new RegExpException(fileName);
        }
    }

    public EpisodeInfos getEpisodeInfos() {
        return episodeInfos;
    }

    public void setEpisodeInfos(EpisodeInfos episodeInfos) {
        this.episodeInfos = episodeInfos;
    }
}
